/*
 * @Author: zhaoqr
 * @Date: 2024-09-27
 * @LastEditTime: 2024-09-27
 * @LastEditors: zhaoqr zhaoqr@channelsoft.com
 * @Description: 
 * @FilePath: \vue3-template\src\utils\reduce.ts
 */

// reduce方法
export default function reduce<T>(array: Array<T>, callback: (accumulator: T, currentValue: T) => T, initialValue: T): T {
  // 遍历开始的索引，如果无初始值，则从1开始，否则从0开始
  let startIndex = 0;
  let result = initialValue;
  // 判断是否传入初始值
  if (initialValue == undefined && array.length == 0) { 
    throw new Error('reduce函数必须传入初始值');
  }
  if (initialValue == undefined && array.length > 0) { 
    startIndex = 1;
    initialValue = array[0] as T;
  }
  for (let i = startIndex; i < array.length; i++) { 
    result = callback(result, array[i] as T);
  }
  return result;
}